<template>
  <div class="upload-container">
    <div class="upload-header">
      <el-icon class="back-btn" :size="24" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <h1 class="upload-title">发布视频</h1>
      <el-button 
        type="primary" 
        :disabled="!canPublish" 
        :loading="isPublishing"
        @click="handlePublish"
      >
        {{ isPublishing ? '发布中...' : '发布' }}
      </el-button>
    </div>
    
    <div class="upload-content">
      <el-scrollbar class="upload-scroll">
        <div class="upload-form">
          <!-- 文件上传区域 -->
          <div class="upload-area">
            <h3>上传文件</h3>
            
            <!-- 视频上传 -->
            <div class="upload-section">
              <h4>选择视频文件</h4>
              <el-upload
                ref="videoUploadRef"
                class="video-upload"
                :action="videoUploadAction"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeVideoUpload"
                :on-success="handleVideoSuccess"
                :on-error="handleVideoError"
                :on-progress="handleVideoProgress"
                accept=".mp4,.avi,.mov,.wmv,.flv,.webm"
                drag
              >
                <div v-if="!videoFile" class="upload-dragger">
                  <el-icon class="upload-icon"><UploadFilled /></el-icon>
                  <div class="upload-text">
                    <p>将视频文件拖拽到此处</p>
                    <p class="upload-hint">或点击选择文件</p>
                    <p class="upload-format">支持 mp4、avi、mov、wmv、flv、webm 格式，最大100MB</p>
                  </div>
                </div>
                <div v-else class="video-preview">
                  <video :src="videoPreviewUrl" controls muted />
                  <div class="video-info">
                    <p><strong>{{ videoFile.name }}</strong></p>
                    <p>大小: {{ formatFileSize(videoFile.size) }}</p>
                    <el-button type="danger" size="small" @click="removeVideo">
                      <el-icon><Delete /></el-icon>
                      重新选择
                    </el-button>
                  </div>
                </div>
              </el-upload>
              
              <!-- 上传进度 -->
              <div v-if="videoUploadProgress > 0 && videoUploadProgress < 100" class="upload-progress">
                <el-progress 
                  :percentage="videoUploadProgress" 
                  :status="videoUploadProgress === 100 ? 'success' : ''"
                />
                <p>视频上传中 {{ videoUploadProgress }}%</p>
              </div>
            </div>
            
            <!-- 封面上传 -->
            <div class="upload-section">
              <h4>选择封面图片（可选）</h4>
              <el-upload
                ref="coverUploadRef"
                class="cover-upload"
                :action="imageUploadAction"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeCoverUpload"
                :on-success="handleCoverSuccess"
                :on-error="handleCoverError"
                :on-progress="handleCoverProgress"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.webp"
              >
                <div v-if="!coverFile" class="cover-uploader">
                  <el-icon class="cover-upload-icon"><Plus /></el-icon>
                  <div class="cover-upload-text">选择封面</div>
                </div>
                <div v-else class="cover-preview">
                  <img :src="coverPreviewUrl" alt="封面预览" />
                  <div class="cover-mask">
                    <el-button type="danger" size="small" @click="removeCover">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
              </el-upload>
              
              <!-- 封面上传进度 -->
              <div v-if="coverUploadProgress > 0 && coverUploadProgress < 100" class="upload-progress">
                <el-progress 
                  :percentage="coverUploadProgress" 
                  :status="coverUploadProgress === 100 ? 'success' : ''"
                />
                <p>封面上传中 {{ coverUploadProgress }}%</p>
              </div>
            </div>
          </div>
          
          <!-- 视频信息表单 -->
          <div v-if="videoUrl" class="video-info-section">
            <h3>视频信息</h3>
            <el-form :model="videoForm" :rules="formRules" ref="formRef" label-width="120px">
              <el-form-item label="视频标题" prop="title">
                <el-input
                  v-model="videoForm.title"
                  placeholder="添加能够描述你视频内容的标题"
                  maxlength="100"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              
              <el-form-item label="视频描述" prop="description">
                <el-input
                  v-model="videoForm.description"
                  placeholder="添加视频描述，让更多人发现你的视频"
                  maxlength="500"
                  show-word-limit
                  :rows="4"
                  type="textarea"
                  resize="none"
                />
              </el-form-item>
              
              <!-- 自动检测的视频信息 -->
              <div v-if="videoMetadata" class="video-metadata">
                <h4>视频信息（自动检测）</h4>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="时长">{{ formatDuration(videoMetadata.duration) }}</el-descriptions-item>
                  <el-descriptions-item label="尺寸">{{ videoMetadata.width }} × {{ videoMetadata.height }}</el-descriptions-item>
                  <el-descriptions-item label="文件大小">{{ formatFileSize(videoFile?.size || 0) }}</el-descriptions-item>
                  <el-descriptions-item label="格式">{{ videoFile?.type || '未知' }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </el-form>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadVideoFile, uploadImageFile, publishVideo } from '@/api/video'
import { ArrowLeft, UploadFilled, Plus, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const videoUploadRef = ref()
const coverUploadRef = ref()

// 文件相关状态
const videoFile = ref(null)
const coverFile = ref(null)
const videoPreviewUrl = ref('')
const coverPreviewUrl = ref('')
const videoUrl = ref('')
const coverUrl = ref('')
const videoUploadProgress = ref(0)
const coverUploadProgress = ref(0)
const videoMetadata = ref(null)

// 表单状态
const isPublishing = ref(false)
const videoForm = reactive({
  title: '',
  description: ''
})

// 上传配置
const videoUploadAction = ref('/api/upload/video')
const imageUploadAction = ref('/api/upload/image')
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const canPublish = computed(() => {
  return videoUrl.value && videoForm.title.trim()
})

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 时长格式化
const formatDuration = (seconds) => {
  if (!seconds) return '未知'
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 视频上传前检查
const beforeVideoUpload = (file) => {
  const isValidType = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/x-flv', 'video/webm'].includes(file.type) ||
                     /\.(mp4|avi|mov|wmv|flv|webm)$/i.test(file.name)
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isValidType) {
    ElMessage.error('视频格式不支持！支持 mp4、avi、mov、wmv、flv、webm 格式')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频文件大小不能超过 100MB!')
    return false
  }

  videoFile.value = file
  videoPreviewUrl.value = URL.createObjectURL(file)
  
  // 获取视频元数据
  getVideoMetadata(file)
  
  return true
}

// 获取视频元数据
const getVideoMetadata = (file) => {
  const video = document.createElement('video')
  video.preload = 'metadata'
  video.onloadedmetadata = () => {
    videoMetadata.value = {
      duration: video.duration,
      width: video.videoWidth,
      height: video.videoHeight
    }
    URL.revokeObjectURL(video.src)
  }
  video.src = URL.createObjectURL(file)
}

// 视频上传成功
const handleVideoSuccess = (response) => {
  console.log('视频上传成功:', response)
  if (response.code === 200) {
    videoUrl.value = response.data.videoUrl
    ElMessage.success('视频上传成功！')
    videoUploadProgress.value = 100
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 视频上传失败
const handleVideoError = (error) => {
  console.error('视频上传失败:', error)
  ElMessage.error('视频上传失败，请重试')
  videoUploadProgress.value = 0
}

// 视频上传进度
const handleVideoProgress = (event) => {
  videoUploadProgress.value = Math.round(event.percent)
}

// 删除视频
const removeVideo = () => {
  videoFile.value = null
  videoPreviewUrl.value = ''
  videoUrl.value = ''
  videoUploadProgress.value = 0
  videoMetadata.value = null
  if (videoPreviewUrl.value) {
    URL.revokeObjectURL(videoPreviewUrl.value)
  }
}

// 封面上传前检查
const beforeCoverUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('图片格式不支持！支持 jpg、jpeg、png、gif、bmp、webp 格式')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片文件大小不能超过 10MB!')
    return false
  }

  coverFile.value = file
  coverPreviewUrl.value = URL.createObjectURL(file)
  
  return true
}

// 封面上传成功
const handleCoverSuccess = (response) => {
  console.log('封面上传成功:', response)
  if (response.code === 200) {
    coverUrl.value = response.data.imageUrl
    ElMessage.success('封面上传成功！')
    coverUploadProgress.value = 100
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 封面上传失败
const handleCoverError = (error) => {
  console.error('封面上传失败:', error)
  ElMessage.error('封面上传失败，请重试')
  coverUploadProgress.value = 0
}

// 封面上传进度
const handleCoverProgress = (event) => {
  coverUploadProgress.value = Math.round(event.percent)
}

// 删除封面
const removeCover = () => {
  coverFile.value = null
  coverPreviewUrl.value = ''
  coverUrl.value = ''
  coverUploadProgress.value = 0
  if (coverPreviewUrl.value) {
    URL.revokeObjectURL(coverPreviewUrl.value)
  }
}

// 返回上一页
const goBack = async () => {
  if (videoFile.value || coverFile.value || videoForm.title || videoForm.description) {
    try {
      await ElMessageBox.confirm(
        '离开此页面将丢失所有更改，确定要离开吗？',
        '确认离开',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return
    }
  }
  
  // 清理对象URL
  if (videoPreviewUrl.value) URL.revokeObjectURL(videoPreviewUrl.value)
  if (coverPreviewUrl.value) URL.revokeObjectURL(coverPreviewUrl.value)
  
  if (window.history.length > 1) {
    router.go(-1)
  } else {
    router.push('/')
  }
}

// 发布视频
const handlePublish = async () => {
  try {
    await formRef.value?.validate()
    
    isPublishing.value = true
    
    const publishData = {
      title: videoForm.title,
      description: videoForm.description || undefined,
      videoUrl: videoUrl.value,
      coverUrl: coverUrl.value || undefined,
      duration: videoMetadata.value?.duration ? Math.round(videoMetadata.value.duration) : undefined,
      fileSize: videoFile.value?.size || undefined,
      width: videoMetadata.value?.width || undefined,
      height: videoMetadata.value?.height || undefined
    }
    
    // 移除undefined值
    Object.keys(publishData).forEach(key => {
      if (publishData[key] === undefined) {
        delete publishData[key]
      }
    })
    
    console.log('发布数据:', publishData)
    
    await publishVideo(publishData)
    
    ElMessage.success('视频发布成功！')
    
    // 清理对象URL
    if (videoPreviewUrl.value) URL.revokeObjectURL(videoPreviewUrl.value)
    if (coverPreviewUrl.value) URL.revokeObjectURL(coverPreviewUrl.value)
    
    router.push('/')
    
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '发布失败，请重试')
  } finally {
    isPublishing.value = false
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.upload-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #ffffff;
  border-bottom: 1px solid #e1e1e1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
  .back-btn {
    cursor: pointer;
    color: #333333;
    transition: all 0.2s ease;
    
    &:hover {
      color: #fe2c55;
      transform: translateX(-2px);
    }
  }
  
  .upload-title {
    font-size: 18px;
    font-weight: 600;
    color: #333333;
    margin: 0;
  }
}

.upload-content {
  flex: 1;
  overflow: hidden;
}

.upload-scroll {
  height: 100%;
}

.upload-form {
  max-width: 900px;
  margin: 0 auto;
  padding: 24px;
}

.upload-area,
.video-info-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333333;
    margin: 0 0 20px 0;
    border-bottom: 2px solid #fe2c55;
    padding-bottom: 8px;
  }
}

.upload-section {
  margin-bottom: 32px;
  
  h4 {
    font-size: 16px;
    font-weight: 500;
    color: #333333;
    margin: 0 0 16px 0;
  }
}

.video-upload {
  :deep(.el-upload) {
    width: 100%;
  }
  
  :deep(.el-upload-dragger) {
    width: 100%;
    height: 200px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #fe2c55;
      background-color: #fafafa;
    }
  }
}

.upload-dragger {
  text-align: center;
  
  .upload-icon {
    font-size: 48px;
    color: #c0c4cc;
    margin-bottom: 16px;
  }
  
  .upload-text {
    p {
      margin: 4px 0;
      
      &:first-child {
        font-size: 16px;
        color: #333333;
      }
      
      &.upload-hint {
        font-size: 14px;
        color: #666666;
      }
      
      &.upload-format {
        font-size: 12px;
        color: #999999;
      }
    }
  }
}

.video-preview {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  
  video {
    width: 300px;
    height: 200px;
    border-radius: 8px;
    background: #000000;
    object-fit: cover;
  }
  
  .video-info {
    flex: 1;
    
    p {
      margin: 8px 0;
      
      &:first-child {
        font-weight: 600;
        color: #333333;
        word-break: break-all;
      }
      
      &:nth-child(2) {
        color: #666666;
        font-size: 14px;
      }
    }
  }
}

.cover-upload {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #fe2c55;
    }
  }
}

.cover-uploader {
  width: 178px;
  height: 178px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .cover-upload-icon {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 8px;
  }
  
  .cover-upload-text {
    color: #8c939d;
    font-size: 14px;
  }
}

.cover-preview {
  position: relative;
  width: 178px;
  height: 178px;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
  }
  
  .cover-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    border-radius: 8px;
    
    &:hover {
      opacity: 1;
    }
  }
}

.upload-progress {
  margin-top: 16px;
  
  p {
    text-align: center;
    margin: 8px 0 0 0;
    font-size: 14px;
    color: #666666;
  }
}

.video-metadata {
  margin-top: 20px;
  
  h4 {
    font-size: 14px;
    color: #666666;
    margin: 0 0 12px 0;
  }
}

@media (max-width: 768px) {
  .upload-form {
    padding: 16px;
  }
  
  .upload-header {
    padding: 12px 16px;
    
    .upload-title {
      font-size: 16px;
    }
  }
  
  .upload-area,
  .video-info-section {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .video-preview {
    flex-direction: column;
    
    video {
      width: 100%;
      max-width: 300px;
    }
  }
  
  .cover-uploader,
  .cover-preview {
    width: 150px;
    height: 150px;
  }
}
</style> 